package com.tange.ai.iot.client.gnssa.firmware

import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.text.TextUtils
import android.view.Window
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import com.tange.ai.iot.client.gnssa.R
import com.tange.ai.iot.client.gnssa.databinding.ActivityFirmwareUpgradeBinding
import com.tange.base.toolkit.*
import com.tange.base.ui.design.BasicDialogLoading
import com.tange.base.ui.design.BasicDialogRequest
import com.tange.core.device.manage.version.DeviceFirmware
import com.tange.core.device.manage.version.FirmwareVersion
import com.tg.appcommon.android.TGLog

class FirmwareUpgradeActivity : AppCompatActivity() {

    companion object {
        private const val TAG = "FirmwareUpgradeActivity_"
        private const val PARAM_DEVICE_ID = "PARAM_DEVICE_ID"
        private const val INTERVAL = 5000L
        private const val TIMEOUT = 3 * 60 * 1000L

        fun launch(context: Context, deviceId: String) {
            context.startActivity(Intent(context, FirmwareUpgradeActivity::class.java).apply {
                putExtra(PARAM_DEVICE_ID, deviceId)
            })
        }
    }

    private lateinit var binding: ActivityFirmwareUpgradeBinding
    private lateinit var deviceId: String
    private var loading: BasicDialogLoading? = null

    private var firmwareVersion: FirmwareVersion? = null

    private val timeoutHandler = Handler(Looper.getMainLooper())
    private val intervalHandler = Handler(Looper.getMainLooper())

    private var targetVersion = ""

    private var stopped = false

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        StatusBarUtil.setLightStatusBar(this, true)
        StatusNavUtils.setStatusBarColor(this, ContextCompat.getColor(this, R.color.app_background))
        requestWindowFeature(Window.FEATURE_NO_TITLE)

        deviceId = intent.getStringExtra(PARAM_DEVICE_ID)!!

        binding = ActivityFirmwareUpgradeBinding.inflate(layoutInflater).apply {
            setContentView(root)
            supportActionBar?.hide()
            root.paddingStatusBar()
        }

        binding.top.left.onClicked { finish() }

        loading = BasicDialogLoading(this).apply {
            setMessage("升级中，请稍候...")
        }


        binding.available.onClicked {
            firmwareVersion?.available?.let {

                if (TextUtils.isEmpty(it.version)) {
                    return@let
                }

                loading?.show()

                targetVersion = it.version!!

                DeviceFirmware.performUpgrade(deviceId, targetVersion, true) {
                    TGLog.i(TAG, "[onCreate][performUpgrade] $it")

                    if (it.success) {
                        Tips.show("触发成功")



                        timeoutHandler.removeCallbacksAndMessages(null)
                        timeoutHandler.postDelayed({
                            if (this@FirmwareUpgradeActivity.isFinishing || this@FirmwareUpgradeActivity.isDestroyed) {
                                return@postDelayed
                            }
                            intervalHandler.removeCallbacksAndMessages(null)
                            loading?.dismiss()
                            Tips.show("升级超时！")
                            stopped = true
                        }, TIMEOUT)

                        queryInterval()

                    } else {
                        loading?.dismiss()
                        BasicDialogRequest(this@FirmwareUpgradeActivity).apply {
                            setMessage("升级失败： ${it.code}, ${it.message}")
                            setPositiveText("知道了")
                            setPositiveOnClicked {
                                dismiss()
                                finish()
                            }
                        }.show()
                    }
                }

            } ?: kotlin.run {
                Tips.show("无可用更新！")
            }
        }


        queryCurrentFirmware()
    }

    private fun queryCurrentFirmware() {
        DeviceFirmware.queryVersion(deviceId) { it ->

            TGLog.i(TAG, "[onCreate][queryVersion] $it")

            if (!it.success) {
                Tips.show("查询固件信息失败：${it.code}, ${it.message}")
                return@queryVersion
            }

            it.data?.current?.let {
                binding.current.name.text = "当前版本：${it.version}"
                binding.current.arrow.gone()
            }

            it?.data?.available?.let {
                if (!TextUtils.isEmpty(it.version)) {
                    binding.available.name.text = "有新版本：${it.version}"
                    binding.available.name.setTextColor(Color.RED)
                    binding.available.desc.visible()
                    binding.available.desc.text = "更新说明：${it.description}"
                    binding.available.arrow.visible()
                    binding.available.isEnabled = true
                } else {
                    binding.available.arrow.gone()
                    binding.available.name.setTextColor(ContextCompat.getColor(this@FirmwareUpgradeActivity, R.color.green))
                    binding.available.name.text = "已是最新版本！"
                    binding.available.isEnabled = false
                }
            } ?: kotlin.run {
                binding.available.arrow.gone()
                binding.available.name.setTextColor(ContextCompat.getColor(this@FirmwareUpgradeActivity, R.color.green))
                binding.available.name.text = "已是最新版本！"
                binding.available.isEnabled = false
            }

            firmwareVersion = it?.data
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        stopped = true
        intervalHandler.removeCallbacksAndMessages(null)
        timeoutHandler.removeCallbacksAndMessages(null)
    }

    private fun queryInterval() {
        intervalHandler.removeCallbacksAndMessages(null)
        intervalHandler.postDelayed({
            DeviceFirmware.queryStatus(deviceId) {
                TGLog.i(TAG, "[onCreate][queryStatus] $it")

                // 停止轮询的条件：升级成功、或者达到超时
                if ((it.data?.status ?: -1) == 2 && targetVersion == (it.data?.currentVersion ?: "")) {
                    timeoutHandler.removeCallbacksAndMessages(null)
                    loading?.dismiss()
                    Tips.show("升级成功！")
                    queryCurrentFirmware()
                } else if (!stopped) {
                    loading?.setMessage("升级中：${it.data?.description}")
                    queryInterval()
                }
            }
        }, INTERVAL)
    }
}